package com.rockcent.service.impl;

import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.*;
import com.rockcent.mall.lib.domain.enumclass.*;
import com.rockcent.mall.lib.dto.MarketMerchantCooperationMessageDto;
import com.rockcent.mall.lib.dto.ProductDto;
import com.rockcent.mall.lib.repository.*;
import com.rockcent.service.MerchantProductSrv;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.text.MessageFormat;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.stream.Collectors;

/**
 * 产品管理接口
 * Created by zhangjh on 2016/11/23.
 */
@Service
public class MerchantProductSrvImpl implements MerchantProductSrv {

    private Logger log = LoggerFactory.getLogger(MerchantProductSrvImpl.class);

    @Autowired
    private MallRepository mallRepository;


    @Autowired
    private CategoryRepository categoryRepository;

    @Autowired
    private MerchantProductDetailRepository merchantProductDetailRepository;

    @Autowired
    private MerchantProductRepository merchantProductRepository;

    @Autowired
    private MerchantProductMerchantStoresRepository merchantProductMerchantStoresRepository;

    @Autowired
    private MerchantProductCategoriesRepository merchantProductCategoriesRepository;

    @Autowired
    private ExecutorService commonExecutorService;

    @Autowired
    private MerchantGiftPacketRepository merchantGiftPacketRepository;

    @Autowired
    private MallProductAuditRepository mallProductAuditRepository;

    @Autowired
    private MerchantProductStatisticsRepository merchantProductStatisticsRepository;

    @Autowired
    private MerchantStoreRepository merchantStoreRepository;

    @Autowired
    private MerchantGiftPacketProductRepository merchantGiftPacketProductRepository;

    @Autowired
    private MerchantRepository merchantRepository;

    @Autowired
    private MarketMerchantCooperationMessageRepository marketMerchantCooperationMessageRepository;

    @Override
    public void updateProductStatus(Long productId, ProductStatus status) {
        if (ProductStatus.SOLDOUT == status) {

            Product product = merchantProductRepository.findByIdAndIsDeleteAndStatus(productId, Whether.NO, ProductStatus.SELLING);
            if (product != null) {
                product.setStatus(ProductStatus.EXPIRED);
                merchantProductRepository.save(product);
                //被分销过
                List<Product> marketProductList = merchantProductRepository.findByMarketIdAndIsDeleteAndStatusIn(product.getId(), Whether.NO, Arrays.asList(ProductStatus.SOLDOUT, ProductStatus.SELLING));
                if (marketProductList.size() > 0) {
                    updateMarketProductStatus(marketProductList, ProductStatus.EXPIRED, false);
                }


                String content = SysMessageConstants.SYS_PRODUCT_EXPIRED.getContent();
                content = MessageFormat.format(content, product.getName());
                //广播消息
                try {

                    String frontedUrl = SysMessageConstants.SYS_PRODUCT_EXPIRED.getFrontendUrl();
                    frontedUrl = MessageFormat.format(frontedUrl, product.getName());
                    SysMessage message = SysMessageHelper.SINGLETON.createMsgBean(SysMessageConstants.SYS_PRODUCT_EXPIRED, SysMessageType.OP, content);
                    message.setFrontendUrl(frontedUrl);
                    //广播消息
                    SysMessageHelper.SINGLETON.pushMsgByMallAndMerchantId(message, null, product.getMerchantId());
                } catch (Exception e) {
                    log.error("产品过期 sendMessage fail:", e);
                }
            } else {
                log.error("======================>productId:{}的产品不存在", productId);
            }


        } else if (ProductStatus.SELLING == status) {
            Product product = merchantProductRepository.findByIdAndIsDeleteAndStatus(productId, Whether.NO, ProductStatus.SOLDOUT);
            if (product != null) {
                if (product.getMarketId() == null) {
                    Mall mall = mallRepository.findOne(product.getMallId());
                    if (mall.getProdAudit()) {
                        product.setStatus(ProductStatus.WAIT_AUDIT);
                        // 产品审核
                        auditProduct(product);
                    }
                } else {
                    product.setStatus(ProductStatus.SELLING);
                }
                merchantProductRepository.save(product);
                //被分销过
                List<Product> marketProductList = merchantProductRepository.findByMarketIdAndIsDelete(product.getId(), Whether.NO);
                if (marketProductList.size() > 0) {
                    this.updateMarketProductStatus(marketProductList, ProductStatus.SELLING, true);
                }
                //被加入礼包的产品,将礼包重新上架
                this.updateGiftPacketStatus(product.getId(), GiftPacketStatus.S2_SELLING);
            } else {
                log.error("======================>productId:{}的产品不存在", productId);
            }
        }
    }

    @Override
    public void updateProductStatus(ProductStatus status, List<Long> productIds) {

        if (null != productIds && productIds.size() > 0) {
            productIds.forEach(productId -> {
                updateProductStatus(productId, status);
            });
        }


    }


    /**
     * 保存产品详情模型
     *
     * @param productId 产品id
     * @param manual    购买须知
     * @param introduce 图文详情
     */
    @Override
    public void saveProductDetail(Long productId, String manual, String introduce) {
        ProductDetail productDetail = merchantProductDetailRepository.findByProductId(productId);
        if (productDetail == null) {
            productDetail = new ProductDetail();
            productDetail.setProductId(productId);
        }
        // 购买须知
        if (StringUtils.isNotBlank(manual)) {
            productDetail.setManual(manual);
        }
        if (StringUtils.isNotBlank(introduce)) {
            productDetail.setIntroduce(introduce);
        }
        merchantProductDetailRepository.save(productDetail);
    }

    /**
     * 门店设置
     *
     * @param merchantId 产品id
     */
    @Override
    public void saveProductMerchantStores(final ProductDto productDto, Long merchantId) {
        if (ProductMerchantStoreType.PART == ProductMerchantStoreType.valueOf(productDto.getProductMerchantStoreType())) {

            productDto.getMerchantStoreIds().forEach(storeId -> {
                ProductMerchantStores productMerchantStores = new ProductMerchantStores();
                productMerchantStores.setMerchantId(merchantId);
                productMerchantStores.setProductId(productDto.getId());
                productMerchantStores.setMerchantStoreId(storeId);
                merchantProductMerchantStoresRepository.save(productMerchantStores);
            });
        }
    }

    /**
     * 品类
     */
    @Override
    public void saveProductCategories(final ProductDto productDto) {
        if (productDto.getCategoryIds() != null && productDto.getCategoryIds().size() > 0) {
            merchantProductCategoriesRepository.deleteByProductId(productDto.getId());
            productDto.getCategoryIds().forEach(categoryId -> {
                ProductCategories categories = new ProductCategories();
                categories.setProductId(productDto.getId());
                categories.setCategoryId(categoryId);
                merchantProductCategoriesRepository.save(categories);
            });
        }
    }


    /**
     * 门店名称列表
     *
     * @param type
     * @param productId
     * @param merchantId
     * @return
     */
    @Override
    public String getProductStoreNames(ProductMerchantStoreType type, Long productId, Long merchantId) {
        String storeName = "";
        if (type == null) {
            storeName = "";
        } else if (type.equals(ProductMerchantStoreType.ALL)) {
            storeName = "ALL";
        } else if (type.equals(ProductMerchantStoreType.PART)) {
            if (productId != null && merchantId != null) {
                List<ProductMerchantStores> productMerchantStoresList = merchantProductMerchantStoresRepository.findByProductIdAndMerchantId(productId, merchantId);
                if (productMerchantStoresList != null && productMerchantStoresList.size() > 0) {
                    StringBuilder sb = new StringBuilder();
                    for (ProductMerchantStores stores : productMerchantStoresList) {
                        MerchantStore store = merchantStoreRepository.findOne(stores.getMerchantStoreId());
                        sb.append(store.getName()).append(" ");
                    }
                    storeName = sb.toString();
                }
            }
        }
        return storeName;
    }

    /**
     * 异步更新分销市场产品属性
     *
     * @param product
     * @param productList
     */
    @Override
    public void updateMarketProductInfo(Product product, List<Product> productList) {
        // 异步任务
        commonExecutorService.execute(() -> {
            for (Product marketProduct : productList) {
                marketProduct.setName(product.getName());
                marketProduct.setLogoUrl(product.getLogoUrl());
                marketProduct.setBarcode(product.getBarcode());
                marketProduct.setDateSelling(product.getDateSelling());
                marketProduct.setLimitCount(product.getLimitCount());
                marketProduct.setShareFee(product.getShareFee());
                marketProduct.setLogoUrls(product.getLogoUrls());
                marketProduct.setNote(product.getNote());
                marketProduct.setResellFee(product.getResellFee());
                marketProduct.setSellPrice(product.getSellPrice());
                marketProduct.setMarketMerchantName(product.getMerchantName());
                marketProduct.setShippingType(product.getShippingType());
                merchantProductRepository.save(marketProduct);
            }
        });

    }

    /**
     * @param merchant
     */
    @Override
    public void updateMerchantProductInfo(Merchant merchant) {

        List<Product> products = merchantProductRepository.findByMallIdAndMerchantIdAndIsDelete(merchant.getMallId(), merchant.getId(), Whether.NO);
        for (Product marketProduct : products) {
            marketProduct.setMerchantName(merchant.getName());
            merchantProductRepository.save(marketProduct);
        }
        products.forEach(product -> {
            List<Product> marketProduct = merchantProductRepository.findByMarketIdAndIsDelete(product.getId(), Whether.NO);
            for (Product p : marketProduct) {
                p.setMarketMerchantName(merchant.getName());
                merchantProductRepository.save(p);
            }
        });


    }

    /**
     * 异步更新被分销过产品(供应商删除产品)
     *
     * @param productList
     */
    @Override
    public void updateMarketProductStatus(List<Product> productList, ProductStatus status, boolean recommend) {
        // 异步任务
        commonExecutorService.execute(() -> {
            for (Product marketProduct : productList) {
                marketProduct.setStatus(status);
                marketProduct.setRecommend(recommend);
                merchantProductRepository.save(marketProduct);
            }
        });
    }

    /**
     * 产品审核
     *
     * @param product
     */
    @Override
    public void auditProduct(Product product) {
        MallProductAudit productAudit = new MallProductAudit();
        productAudit.setProductId(product.getId());
        productAudit.setMerchantId(product.getMerchantId());
        productAudit.setMerchantName(product.getMerchantName());
        productAudit.setProductName(product.getName());
        productAudit.setStatus(MallProductAuditStatus.UNAUDITED);
        productAudit.setIsPass(Whether.NO);
        productAudit.setType(product.getType());
        mallProductAuditRepository.save(productAudit);

    }

    /**
     * 产品统计新建
     *
     * @param product
     * @return
     */
    @Override
    public void productStatisticsSave(Product product) {
        ProductStatistics productStatistics = new ProductStatistics();
        productStatistics.setProductId(product.getId());
        productStatistics.setMallId(product.getMallId());
        productStatistics.setMerchantId(product.getMerchantId());
        merchantProductStatisticsRepository.save(productStatistics);
    }

    /**
     * 异步更新产品下架状态
     *
     * @param productList
     * @param status
     */
    @Override
    public void updateProductStatus(List<Product> productList, ProductStatus status) {
        //异步任务
        commonExecutorService.execute(() -> {
            if (productList != null && productList.size() > 0) {
                for (Product product : productList) {
                    product.setStatus(status);
                    merchantProductRepository.save(product);
                }
            }
        });

    }

    /**
     * 组装上级名称
     *
     * @param categoriesId 品类ID
     * @return
     */
    @Override
    public StringBuilder parentName(Long categoriesId) {
        StringBuilder sb = new StringBuilder();
        Category category = categoryRepository.findOne(categoriesId);
        if (category.getParentId() != null) {
            Category parent = categoryRepository.findOne(category.getParentId());
            sb.append(parent.getName()).append("--");
        }
        sb.append(category.getName()).append("--");
        return sb;
    }

    @Override
    public List<Long> findAllSoldoutProductIds() {

        return merchantProductRepository.findAllSoldoutProductIds();
    }

    /**
     * 被加入礼包的产品,
     *
     * @param productId 产品Id
     */
    @Override
    public void updateGiftPacketStatus(Long productId, GiftPacketStatus status) {
        //异步任务
        commonExecutorService.execute(() -> {
            List<MerchantGiftPacketProduct> giftPacketProductList = merchantGiftPacketProductRepository.findByProductId(productId);
            if (giftPacketProductList.size() > 0) {
                List<Long> packetIds = giftPacketProductList.stream().map(MerchantGiftPacketProduct::getPacketId).collect(Collectors.toList());
                List<MerchantGiftPacket> giftPacketList = merchantGiftPacketRepository.findByIdIn(packetIds);
                giftPacketList.forEach(giftPacket -> {
                    giftPacket.setStatus(status);
                    merchantGiftPacketRepository.save(giftPacket);
                    if (GiftPacketStatus.S2_SELLING != status) {
                        List<MerchantGiftPacket> merchantGiftPacketList = merchantGiftPacketRepository.findByMarketId(giftPacket.getId());
                        merchantGiftPacketList.forEach(packet -> {
                            packet.setStatus(status);
                            merchantGiftPacketRepository.save(packet);
                        });
                    }
                });
            }
        });
    }

    /**
     * 向分销商发送产品上架或下架消息
     *
     * @param productIds
     * @param status
     */
    @Override
    public void sendProductMsgToDistributorMerchant(List<Long> productIds, ProductStatus status) {
        if (productIds != null && productIds.size() > 0) {
            for (Long productId : productIds) {
                ProductStatus productStatus = null;
                if (ProductStatus.SOLDOUT == status) {
                    productStatus = ProductStatus.SELLING;
                } else if (ProductStatus.SELLING == status) {
                    productStatus = ProductStatus.SOLDOUT;
                }
                findProductAndMarket(productId, productStatus);
            }
        }
    }

    /**
     * 通过产品ID查询产品与分销信息
     *
     * @param productId
     * @param status
     */
    private void findProductAndMarket(Long productId, ProductStatus status) {
        Product product = findProductByProductIdAndStatus(productId, status);
        if (product != null) {
            ProductStatus productStatus = null;
            if (ProductStatus.SELLING == status) {
                productStatus = ProductStatus.SOLDOUT;
            } else if (ProductStatus.SOLDOUT == status) {
                productStatus = ProductStatus.SELLING;
            }
            //被分销过
            List<Product> marketProductList = findMarketProductListByMarketId(product.getId());
            if (marketProductList != null && marketProductList.size() > 0) {
                //供应商
                Merchant merchant = merchantRepository.findOne(product.getMerchantId());
                if (merchant != null) {
                    String supplierMerchantName = merchant.getName();
                    for (Product p : marketProductList) {
                        sendProductMsg(supplierMerchantName, p.getId(), p.getName(), productStatus, p.getMerchantId());
                    }
                }
            }
        }
    }

    /**
     * 通过产品ID与状态查询
     *
     * @param productId
     * @param status
     * @return
     */
    private Product findProductByProductIdAndStatus(Long productId, ProductStatus status) {
        Product product = null;
        if (productId != null) {
            product = merchantProductRepository.findByIdAndIsDeleteAndStatus(productId, Whether.NO, status);
        }
        return product;
    }

    /**
     * 通赤分销产品ID查询列表
     *
     * @param marketId
     * @return
     */
    private List<Product> findMarketProductListByMarketId(Long marketId) {
        List<Product> marketProductList = null;
        if (marketId != null) {
            marketProductList = merchantProductRepository.findByMarketIdAndIsDelete(marketId, Whether.NO);
        }
        return marketProductList;
    }

    /**
     * 向分销商发送产品上架或下架消息
     *
     * @param dto
     */
    public void sendProductMsgDto(MarketMerchantCooperationMessageDto dto) {
        if (dto != null) {
            //异步任务
            commonExecutorService.execute(() -> {
                MarketMerchantCooperationMessage message = new MarketMerchantCooperationMessage();
                message.setTitle(dto.getTitle());
                message.setContent(dto.getContent());
                message.setMerchantId(dto.getMerchantId());
                marketMerchantCooperationMessageRepository.save(message);
            });
        }
    }

    /**
     * 向分销商发送产品上架或下架消息
     *
     * @param supplierMerchantName
     * @param productId
     * @param productName
     * @param status
     */
    public void sendProductMsg(String supplierMerchantName, Long productId, String productName, ProductStatus status, Long merchantId) {
        String title = "";
        String content = "";
        if (ProductStatus.SOLDOUT == status) {
            title = "产品下架";
            content = String.format("尊敬的客户，%s已将%s编号为%s的产品下架，您暂时无法销售该产品，请知悉。", supplierMerchantName, productName, String.valueOf(productId));
        } else if (ProductStatus.SELLING == status) {
            title = "产品上架";
            content = String.format("尊敬的客户，%s已将%s编号为%s的产品重新上架，您可以重新上架销售该产品，请知悉。", supplierMerchantName, productName, String.valueOf(productId));
        }
        MarketMerchantCooperationMessageDto dto = new MarketMerchantCooperationMessageDto();
        dto.setTitle(title);
        dto.setMerchantId(merchantId);
        dto.setContent(content);
        sendProductMsgDto(dto);
    }
}
